blog

home / developersection / blogs / reflection in c#

Reflection in C#

priyanka kushwaha 2992 27-Jan-2015

 In this blog, I’m explaining about Reflection in .Net

Reflection is the process by which program can read its own metadata. Reflection provides objects (typeof Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables to access them.

Example
namespace ReflectionProgram
{
 public class Operation
    {
    public  int add(int x, int y)
        {
            return (x + y);
        }
 
      public  int subtract(int x, int y)
        {
            return (x - y);
        }
      private string topic;
    }
 
 
   
  class Program
    {
        static void Main(string[] args)
        {
           Type  t  =typeof(Operation);
           MemberInfo[] mi = t.GetMethods();
            object[] parameters = new object[2];
            parameters[0] = 32;
            parameters[1] = 12;
           object obj =Activator.CreateInstance(t);
              int res = (int)t.InvokeMember(mi[3].Name, BindingFlags.InvokeMethod,null, obj, parameters);
               Console.WriteLine(res);
           var info = typeof(System.Int32).Assembly;
           Console.WriteLine(info);
           Console.ReadKey();
        }
    }
}

Updated 27-Jan-2015

Leave Comment

1 Comments

Comments

Liked By